package com.example.doctorsystem.dao;

import com.example.doctorsystem.model.Doctor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class DoctorDaoImpl implements DoctorDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private Doctor mapRow(ResultSet rs, int rowNum) throws SQLException {
        Doctor doctor = new Doctor();
        doctor.setId(rs.getInt("id"));
        doctor.setName(rs.getString("name"));
        doctor.setEmail(rs.getString("email"));
        doctor.setPassword(rs.getString("password"));
        doctor.setDepartment(rs.getString("department"));
        doctor.setCreateTime(rs.getTimestamp("create_time"));
        return doctor;
    }

    @Override
    public int registerDoctor(Doctor doctor) {
        String sql = "INSERT INTO doctors(name, email, password, department) VALUES (?, ?, ?, ?)";
        return jdbcTemplate.update(sql, doctor.getName(), doctor.getEmail(), doctor.getPassword(), doctor.getDepartment());
    }

    @Override
    public Doctor loginDoctor(String email, String password) {
        String sql = "SELECT * FROM doctors WHERE email = ? AND password = ?";
        List<Doctor> list = jdbcTemplate.query(sql, this::mapRow, email, password);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public List<Doctor> findAllDoctors() {
        String sql = "SELECT * FROM doctors ORDER BY create_time DESC";
        return jdbcTemplate.query(sql, this::mapRow);
    }
    @Override
    public Doctor getDoctorById(int id) {
        String sql = "SELECT * FROM doctors WHERE id = ?";
        List<Doctor> list = jdbcTemplate.query(sql, (rs, rowNum) -> {
            Doctor doctor = new Doctor();
            doctor.setId(rs.getInt("id"));
            doctor.setName(rs.getString("name"));
            doctor.setEmail(rs.getString("email"));
            doctor.setPassword(rs.getString("password"));
            return doctor;
        }, id);
        return list.isEmpty() ? null : list.get(0);
    }

}
